package com.jf.jsp.exercise1;

import com.jf.jsp.utils.WebUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Created with IntelliJ IDEA
 * Description:
 * User:22954
 * Date:2024-08-31
 * Time:15:00
 */
@WebServlet(name = "CalServlet", urlPatterns = "/calServlet")
public class CalServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String num1 = req.getParameter("num1");
        String num2 = req.getParameter("num2");
        String operator = req.getParameter("operator");
        String[] warnings = WebUtil.getWarnings(num1, num2, operator);
        if (warnings[0] != null || warnings[1] != null || warnings[2] != null) {
            System.out.println(warnings[0]);
            req.setAttribute("warning", warnings);
            req.getRequestDispatcher("/exercise/cal.jsp").forward(req, resp);
        }
        int n1 = Integer.parseInt(num1);
        int n2 = Integer.parseInt(num2);
        double ret = 0.0;
        switch (operator) {
            case "+":
                ret = n1 + n2;
                break;
            case "-":
                ret = n1 - n2;
                break;
            case "*":
                ret = n1 * n2;
                break;
            case "/":
                ret = (double) n1 / n2;
                break;
        }
        String result = String.format("%s %s %s = %s", num1, operator, num2, ret);
        req.setAttribute("result", result);
        req.getRequestDispatcher("/exercise/result.jsp").forward(req, resp);
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }
}
